<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">
<script>
    (function () {
        if ('') {
            if (prompt('请输入文章密码') !== '') {
                alert('密码错误！');
                if (history.length === 1) {
                    location.replace("https://google.com"); // 这里替换成你的首页
                } else {
                    history.back();
                }
            }
        }
    })();
</script>








<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="php,">










<meta name="description" content="本文转自laravel-china 依赖注入1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071&amp;lt;?phpclass Car&amp;#123;    //汽车可以跑,定义一个方法 run">
<meta name="keywords" content="php">
<meta property="og:type" content="article">
<meta property="og:title" content="PHP依赖注入">
<meta property="og:url" content="http://yoursite.com/2018/11/23/PHP依赖注入/index.html">
<meta property="og:site_name" content="苏生不惑的博客">
<meta property="og:description" content="本文转自laravel-china 依赖注入1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071&amp;lt;?phpclass Car&amp;#123;    //汽车可以跑,定义一个方法 run">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2019-10-11T09:26:57.026Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="PHP依赖注入">
<meta name="twitter:description" content="本文转自laravel-china 依赖注入1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071&amp;lt;?phpclass Car&amp;#123;    //汽车可以跑,定义一个方法 run">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://yoursite.com/2018/11/23/PHP依赖注入/">



<meta name="referrer" content="never"> ​​​​


  <title>PHP依赖注入 | 苏生不惑的博客</title>
  








</head>

<body itemscope="" itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope="" itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">苏生不惑的博客</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br>
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope="" itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/2018/11/23/PHP依赖注入/">

    <span hidden itemprop="author" itemscope="" itemtype="http://schema.org/Person">
      <meta itemprop="name" content="苏生不惑">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope="" itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="苏生不惑的博客">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">PHP依赖注入</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-11-23T16:46:31+08:00">
                2018-11-23
              </time>
            

            

            
          </span>

          

          
            
          

          
          

          
            <span class="post-meta-divider">|</span>
            <span class="page-pv"><i class="fa fa-file-o"></i>
            <span class="busuanzi-value" id="busuanzi_value_page_pv"></span>次
            </span>
          

          
            <div class="post-wordcount">
              
                
                  <span class="post-meta-divider">|</span>
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  3.8k 字
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  17 分钟
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>本文转自<a href="https://laravel-china.org/articles/19554" target="_blank" rel="noopener">laravel-china</a></p>
<h3 id="依赖注入"><a href="#依赖注入" class="headerlink" title="依赖注入"></a>依赖注入</h3><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br></pre></td><td class="code"><pre><span class="line">&lt;?php</span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Car</span></span></span><br><span class="line"><span class="class"></span>&#123;</span><br><span class="line">    <span class="comment">//汽车可以跑,定义一个方法 run()</span></span><br><span class="line">    public <span class="function"><span class="keyword">function</span> <span class="title">run</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="string">'滴滴滴,车开了'</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Person</span></span></span><br><span class="line"><span class="class"></span>&#123;</span><br><span class="line">    private $car = <span class="literal">null</span>;<span class="comment">//保存某人的车,暂时还没车</span></span><br><span class="line">    public <span class="function"><span class="keyword">function</span> <span class="title">drive</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">        $<span class="keyword">this</span>-&gt;car = <span class="keyword">new</span> Car();<span class="comment">//要开车先造车,造了一辆车保存在某人的 $car 里</span></span><br><span class="line">        <span class="keyword">return</span> $<span class="keyword">this</span>-&gt;car-&gt;run();<span class="comment">//调用车的 run() 方法</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">$xiaoming = <span class="keyword">new</span> Person();</span><br><span class="line">echo $xiaoming-&gt;drive();<span class="comment">//输出 滴滴滴,车开了</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Car</span></span></span><br><span class="line"><span class="class"></span>&#123;</span><br><span class="line">    <span class="comment">//汽车可以跑,定义一个方法 run()</span></span><br><span class="line">    public <span class="function"><span class="keyword">function</span> <span class="title">run</span>(<span class="params"></span>)</span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="string">'滴滴滴,车开了'</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Person</span></span></span><br><span class="line"><span class="class"></span>&#123;</span><br><span class="line">    private $car = <span class="literal">null</span>;<span class="comment">//保存某人的车,暂时还没车</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">//new 某人的时候,就给他注入一辆车,通过 $a 传入构造方法,并保存在 $car 里</span></span><br><span class="line">    public <span class="function"><span class="keyword">function</span> <span class="title">__construct</span>(<span class="params">$a</span>)</span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        $<span class="keyword">this</span>-&gt;car = $a;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    public <span class="function"><span class="keyword">function</span> <span class="title">drive</span>(<span class="params"></span>)</span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> $<span class="keyword">this</span>-&gt;car-&gt;run();<span class="comment">//调用车的 run() 方法</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line">$car  = <span class="keyword">new</span> Car();<span class="comment">//买一辆车</span></span><br><span class="line">$xiaoming = <span class="keyword">new</span> Person($car);<span class="comment">//new 小明的时候,把刚才买的车注入</span></span><br><span class="line">echo $xiaoming-&gt;drive();<span class="comment">//输出 滴滴滴,车开了</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Car</span></span></span><br><span class="line"><span class="class"></span>&#123;</span><br><span class="line">    <span class="comment">//汽车可以跑,定义一个方法 run()</span></span><br><span class="line">    public <span class="function"><span class="keyword">function</span> <span class="title">run</span>(<span class="params"></span>)</span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="string">'滴滴滴,车开了'</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Person</span></span></span><br><span class="line"><span class="class"></span>&#123;</span><br><span class="line">    private $car = <span class="literal">null</span>;<span class="comment">//保存某人的车,暂时还没车</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">//new 某人的时候,就给他注入一辆车,通过 $a 传入构造方法</span></span><br><span class="line">    public <span class="function"><span class="keyword">function</span> <span class="title">__construct</span>(<span class="params">Car $a</span>)// &lt;----这里做了类型限定</span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        $<span class="keyword">this</span>-&gt;car = $a;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    public <span class="function"><span class="keyword">function</span> <span class="title">drive</span>(<span class="params"></span>)</span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> $<span class="keyword">this</span>-&gt;car-&gt;run();<span class="comment">//调用车的 run() 方法</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="IoC-容器类"><a href="#IoC-容器类" class="headerlink" title="IoC 容器类"></a>IoC 容器类</h3><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//写一个简单的 IoC 容器类</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Container</span></span>&#123;</span><br><span class="line">    private <span class="keyword">static</span> $objArr = [];<span class="comment">//定义一个静态的空数组</span></span><br><span class="line"></span><br><span class="line">    public <span class="keyword">static</span> <span class="function"><span class="keyword">function</span> <span class="title">set</span>(<span class="params">$flag, Callable $func</span>)</span>&#123;</span><br><span class="line">        self::$objArr[$flag] = $func;<span class="comment">//存入键值对,键是一个字符串,作为标识符,值是一个匿名函数</span></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    public <span class="keyword">static</span> <span class="function"><span class="keyword">function</span> <span class="title">get</span>(<span class="params">$flag</span>)</span>&#123;</span><br><span class="line">        $tmp = self::$objArr[$flag];<span class="comment">//取出标识符对应的匿名函数,用$tmp临时保存一下</span></span><br><span class="line">        <span class="keyword">return</span> $tmp();<span class="comment">//在$tmp后名加上括号,表示执行这个函数,并返回</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//下面这条语句执行完毕后,会在 $objArr 里存入一个键值对,键是 car ,值是这个匿名函数,该匿名函数返回的是创建 Car 对象的语句</span></span><br><span class="line">Container::set(<span class="string">'Car'</span>, <span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">new</span> Car();</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line"><span class="comment">//下面这条语句执行完毕后,会在 $objArr 里存入一个键值对,键是 person ,值是这个匿名函数,该匿名函数返回的是创建 Person 对象的语句</span></span><br><span class="line">Container::set(<span class="string">'Person'</span>, <span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">new</span> Person(Container::get(<span class="string">'Car'</span>));<span class="comment">//直接去容器中取一辆车出来,并作为参数传给 Person 类的构造函数</span></span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line">$xiaomin = Container::get(<span class="string">'Person'</span>);<span class="comment">//直接去容器中取一个人出来,取名叫小明</span></span><br><span class="line">echo $xiaomin-&gt;drive();<span class="comment">//输出 滴滴滴,车开了</span></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Container</span></span></span><br><span class="line"><span class="class"></span>&#123;</span><br><span class="line">    protected $binds;</span><br><span class="line"></span><br><span class="line">    protected $instances;</span><br><span class="line"></span><br><span class="line">    public <span class="function"><span class="keyword">function</span> <span class="title">bind</span>(<span class="params">$abstract, $concrete</span>)</span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> ($concrete <span class="keyword">instanceof</span> Closure) &#123;</span><br><span class="line">            $<span class="keyword">this</span>-&gt;binds[$abstract] = $concrete;</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            $<span class="keyword">this</span>-&gt;instances[$abstract] = $concrete;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    public <span class="function"><span class="keyword">function</span> <span class="title">make</span>(<span class="params">$abstract, $parameters = []</span>)</span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (isset($<span class="keyword">this</span>-&gt;instances[$abstract])) &#123;</span><br><span class="line">            <span class="keyword">return</span> $<span class="keyword">this</span>-&gt;instances[$abstract];</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        array_unshift($parameters, $<span class="keyword">this</span>);</span><br><span class="line"></span><br><span class="line">        <span class="keyword">return</span> call_user_func_array($<span class="keyword">this</span>-&gt;binds[$abstract], $parameters);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">//在线执行laravel https://implode.io/4mT8O4</span></span><br><span class="line"> $container = <span class="keyword">new</span> Container;</span><br><span class="line"></span><br><span class="line">    $container-&gt;bind(<span class="string">'Board'</span>, <span class="function"><span class="keyword">function</span>(<span class="params">$container</span>)</span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> CommonBoard;</span><br><span class="line">    &#125;);</span><br><span class="line"></span><br><span class="line">    $container-&gt;bind(<span class="string">'Computer'</span>,<span class="function"><span class="keyword">function</span>(<span class="params">$container,$module</span>)</span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> Computer($container-&gt;make($<span class="built_in">module</span>));</span><br><span class="line">    &#125;);</span><br><span class="line"></span><br><span class="line">    $computer = $container-&gt;make(<span class="string">'Computer'</span>,[<span class="string">'Board'</span>]);</span><br></pre></td></tr></table></figure>
<h3 id="魔术方法"><a href="#魔术方法" class="headerlink" title="魔术方法"></a>魔术方法</h3><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//https://laravel-china.org/articles/20625</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Model</span></span></span><br><span class="line"><span class="class"></span>&#123;</span><br><span class="line">    protected <span class="function"><span class="keyword">function</span> <span class="title">increment</span>(<span class="params">$column, $amount = <span class="number">1</span>, array $extra = []</span>)</span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> $<span class="keyword">this</span>-&gt;incrementOrDecrement($column, $amount, $extra, <span class="string">'increment'</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    public <span class="function"><span class="keyword">function</span> <span class="title">__call</span>(<span class="params">$method, $parameters</span>)</span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (in_array($method, [<span class="string">'increment'</span>, <span class="string">'decrement'</span>])) &#123;</span><br><span class="line">            <span class="keyword">return</span> $<span class="keyword">this</span>-&gt;$method(...$parameters);</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">return</span> $<span class="keyword">this</span>-&gt;forwardCallTo($<span class="keyword">this</span>-&gt;newQuery(), $method, $parameters);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    public <span class="keyword">static</span> <span class="function"><span class="keyword">function</span> <span class="title">__callStatic</span>(<span class="params">$method, $parameters</span>)</span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> (<span class="keyword">new</span> <span class="keyword">static</span>)-&gt;$method(...$parameters);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line">(<span class="keyword">new</span> User)-&gt;increment(<span class="string">'age'</span>);</span><br><span class="line">User::increment(<span class="string">'age'</span>);</span><br><span class="line">第一种，因为我们User继承了Model类，但是increment方法前有个protected导致我们无法从外部访问这个方法。但是不用慌张，这个时候__call魔术方法就起到了效果，他会帮我们去访问increment方法。</span><br><span class="line"></span><br><span class="line">第二种，我们用静态调用increment方法，运行的时候，程序就去找有没有定义的静态increment方法，找了一圈没有找到，怎么办？这个时候__callStatic开始发挥作用。我们用的是User类，因为延迟静态绑定的缘故，可以看成:</span><br><span class="line"></span><br><span class="line"><span class="keyword">return</span> (<span class="keyword">new</span> User)-&gt;increment(<span class="string">'age'</span>);</span><br></pre></td></tr></table></figure>
<h3 id="控制反转"><a href="#控制反转" class="headerlink" title="控制反转"></a>控制反转</h3><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br><span class="line">145</span><br><span class="line">146</span><br><span class="line">147</span><br><span class="line">148</span><br><span class="line">149</span><br><span class="line">150</span><br><span class="line">151</span><br><span class="line">152</span><br><span class="line">153</span><br><span class="line">154</span><br><span class="line">155</span><br><span class="line">156</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Boos</span></span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//领导依赖员工</span></span><br><span class="line">    private $staff;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//现在老板只需要接受 hr 招聘就好，将控制权交给 hr</span></span><br><span class="line">    <span class="comment">//以设置方法来实现依赖注入</span></span><br><span class="line">    public <span class="function"><span class="keyword">function</span> <span class="title">setStaff</span>(<span class="params">Standard $staff</span>)</span>&#123;      </span><br><span class="line">        $<span class="keyword">this</span>-&gt;staff = $staff;</span><br><span class="line">    &#125; </span><br><span class="line"></span><br><span class="line">    public <span class="function"><span class="keyword">function</span> <span class="title">task</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">        $<span class="keyword">this</span>-&gt;staff-&gt;work();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//招聘所设定的标准</span></span><br><span class="line">interface Standard&#123;</span><br><span class="line">    public <span class="function"><span class="keyword">function</span> <span class="title">work</span>(<span class="params"></span>);</span></span><br><span class="line"><span class="function">&#125;</span></span><br><span class="line"><span class="function"></span></span><br><span class="line"><span class="function">//员工需要依赖的标准</span></span><br><span class="line"><span class="function"><span class="title">class</span> <span class="title">StaffA</span> <span class="title">implements</span> <span class="title">Standard</span></span>&#123;</span><br><span class="line">    public <span class="function"><span class="keyword">function</span> <span class="title">work</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">        echo <span class="string">'雇员A有能力能够完成老板指定的工作'</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">StaffB</span> <span class="title">implements</span> <span class="title">Standard</span></span>&#123;</span><br><span class="line">    public <span class="function"><span class="keyword">function</span> <span class="title">work</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">        echo <span class="string">'雇员B有能力能够完成老板指定的工作'</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//ioc容器</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Hr</span></span>&#123;</span><br><span class="line">    public <span class="function"><span class="keyword">function</span> <span class="title">getStagff</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> StaffB();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//公司老板</span></span><br><span class="line">$boos = <span class="keyword">new</span> Boos();</span><br><span class="line"><span class="comment">//老板招的hr</span></span><br><span class="line">$hr = <span class="keyword">new</span> Hr();</span><br><span class="line">$staff = $hr-&gt;getStagff();</span><br><span class="line"><span class="comment">//hr把招到的人给老板（控制反转和依赖注入）</span></span><br><span class="line">$boos-&gt;setStaff($staff);</span><br><span class="line"><span class="comment">//老板让他工作了</span></span><br><span class="line">$boos-&gt;task();</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Boos</span></span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//领导依赖员工</span></span><br><span class="line">    private $staff;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//老板只需要告诉外部我需要什么样的人就好了，其它什么都不管，具体什么样的人交给外部处理。</span></span><br><span class="line">    <span class="comment">//用构造方法方式实现依赖注入</span></span><br><span class="line">    public <span class="function"><span class="keyword">function</span> <span class="title">__construct</span>(<span class="params">Standard $staff</span>)</span>&#123;       </span><br><span class="line">        $<span class="keyword">this</span>-&gt;staff = $staff;</span><br><span class="line">    &#125; </span><br><span class="line"></span><br><span class="line">    public <span class="function"><span class="keyword">function</span> <span class="title">task</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">        $<span class="keyword">this</span>-&gt;staff-&gt;work();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//招聘所设定的标准</span></span><br><span class="line">interface Standard&#123;</span><br><span class="line">    public <span class="function"><span class="keyword">function</span> <span class="title">work</span>(<span class="params"></span>);</span></span><br><span class="line"><span class="function">&#125;</span></span><br><span class="line"><span class="function"></span></span><br><span class="line"><span class="function">//员工需要依赖的标准</span></span><br><span class="line"><span class="function"><span class="title">class</span> <span class="title">StaffA</span> <span class="title">implements</span> <span class="title">Standard</span></span>&#123;</span><br><span class="line">    public <span class="function"><span class="keyword">function</span> <span class="title">work</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">        echo <span class="string">'雇员A有能力能够完成老板指定的工作'</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">StaffB</span> <span class="title">implements</span> <span class="title">Standard</span></span>&#123;</span><br><span class="line">    public <span class="function"><span class="keyword">function</span> <span class="title">work</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">        echo <span class="string">'雇员B有能力能够完成老板指定的工作'</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Hr</span></span>&#123;</span><br><span class="line"></span><br><span class="line">    private $binds = [];</span><br><span class="line"></span><br><span class="line">    <span class="comment">//接受不同员工的简历，并存起来</span></span><br><span class="line">    public <span class="function"><span class="keyword">function</span> <span class="title">bind</span>(<span class="params">$contract,$concrete</span>)</span>&#123;</span><br><span class="line">        $<span class="keyword">this</span>-&gt;binds[$contract] = $concrete;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//询问老板选人的标准由哪些,并且从满足的简历中筛选人</span></span><br><span class="line">    private <span class="function"><span class="keyword">function</span> <span class="title">methodBindParams</span>(<span class="params">$className</span>)</span>&#123;</span><br><span class="line">        $reflect = <span class="keyword">new</span> reflect($className,<span class="string">'__construct'</span>);</span><br><span class="line">        <span class="keyword">return</span> $reflect-&gt;bindParamsToMethod();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//将选好的工作人员交给老板</span></span><br><span class="line">    public <span class="function"><span class="keyword">function</span> <span class="title">make</span>(<span class="params">$className</span>)</span>&#123;</span><br><span class="line">        $methodBindParams = $<span class="keyword">this</span>-&gt;methodBindParams($className);</span><br><span class="line">        $reflect = <span class="keyword">new</span> reflect($className,<span class="string">'__construct'</span>);</span><br><span class="line">        <span class="keyword">return</span> $reflect-&gt;make($<span class="keyword">this</span>-&gt;binds,$methodBindParams);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">reflect</span></span>&#123;</span><br><span class="line">    private $className;</span><br><span class="line"></span><br><span class="line">    private $methodName;</span><br><span class="line"></span><br><span class="line">    public <span class="function"><span class="keyword">function</span> <span class="title">__construct</span>(<span class="params">$className,$methodName</span>)</span>&#123;</span><br><span class="line">        $<span class="keyword">this</span>-&gt;className = $className;</span><br><span class="line">        $<span class="keyword">this</span>-&gt;methodName = $methodName;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//绑定参数到方法</span></span><br><span class="line">    public <span class="function"><span class="keyword">function</span> <span class="title">bindParamsToMethod</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line"></span><br><span class="line">        $params = [];</span><br><span class="line"></span><br><span class="line">        $method  = <span class="keyword">new</span> ReflectionMethod($<span class="keyword">this</span>-&gt;className,$<span class="keyword">this</span>-&gt;methodName);</span><br><span class="line"></span><br><span class="line">        foreach ($method-&gt;getParameters() <span class="keyword">as</span> $param) &#123;</span><br><span class="line">            $params[] =  [$param-&gt;name,$param-&gt;getClass()-&gt;name];</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">return</span> [$<span class="keyword">this</span>-&gt;<span class="function"><span class="params">className</span>=&gt;</span> $params];</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    public <span class="function"><span class="keyword">function</span> <span class="title">make</span>(<span class="params">$bind,$methodBindParams</span>)</span>&#123;</span><br><span class="line">        $args = [];</span><br><span class="line">        foreach ($methodBindParams <span class="keyword">as</span> $className =&gt; $params) &#123;</span><br><span class="line">            foreach ($params <span class="keyword">as</span> $param) &#123;</span><br><span class="line">                list($paramName,$paramType) = $param;</span><br><span class="line"></span><br><span class="line">                $paramName = <span class="keyword">new</span> $bind[$paramType]();</span><br><span class="line"></span><br><span class="line">                array_push($args, $paramName);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        $reflectionClass = <span class="keyword">new</span> ReflectionClass($<span class="keyword">this</span>-&gt;className);</span><br><span class="line">        <span class="keyword">return</span> $reflectionClass-&gt;newInstanceArgs($args);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br><span class="line">$hr = <span class="keyword">new</span> Hr();</span><br><span class="line"></span><br><span class="line"><span class="comment">//老板如果需要换工作人员，只需要绑定其它的工作人员即可。</span></span><br><span class="line">$staff = $hr-&gt;bind(<span class="string">'Standard'</span>,<span class="string">'StaffA'</span>);</span><br><span class="line"></span><br><span class="line">$boos = $hr-&gt;make(<span class="string">'Boos'</span>);</span><br><span class="line"></span><br><span class="line">$boos-&gt;task();</span><br></pre></td></tr></table></figure>
<h3 id="依赖注入原理"><a href="#依赖注入原理" class="headerlink" title="依赖注入原理"></a>依赖注入原理</h3><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br></pre></td><td class="code"><pre><span class="line">&lt;?php</span><br><span class="line"></span><br><span class="line">namespace Database;</span><br><span class="line">use ReflectionMethod;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Database</span></span></span><br><span class="line"><span class="class"></span>&#123;</span><br><span class="line"></span><br><span class="line">    protected $adapter;</span><br><span class="line"></span><br><span class="line">    public <span class="function"><span class="keyword">function</span> <span class="title">__construct</span> (<span class="params"></span>)</span></span><br><span class="line"><span class="function">    </span>&#123;&#125;</span><br><span class="line"></span><br><span class="line">    public <span class="function"><span class="keyword">function</span> <span class="title">test</span> (<span class="params">MysqlAdapter $adapter</span>)</span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        $adapter-&gt;test();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">MysqlAdapter</span></span></span><br><span class="line"><span class="class"></span>&#123;</span><br><span class="line"></span><br><span class="line">    public <span class="function"><span class="keyword">function</span> <span class="title">test</span> (<span class="params"></span>)</span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        echo <span class="string">"i am MysqlAdapter test"</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">app</span></span></span><br><span class="line"><span class="class"></span>&#123;</span><br><span class="line"></span><br><span class="line">    public <span class="keyword">static</span> <span class="function"><span class="keyword">function</span> <span class="title">run</span> (<span class="params">$instance, $method</span>)</span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (! method_exists($instance, $method))</span><br><span class="line"></span><br><span class="line">            <span class="keyword">return</span> <span class="literal">null</span>;</span><br><span class="line"></span><br><span class="line">        $reflector = <span class="keyword">new</span> ReflectionMethod($instance, $method);</span><br><span class="line"></span><br><span class="line">        $parameters = [</span><br><span class="line">                    <span class="number">1</span></span><br><span class="line">            ];</span><br><span class="line">        foreach ($reflector-&gt;getParameters() <span class="keyword">as</span> $key =&gt; $parameter)</span><br><span class="line">        &#123;</span><br><span class="line"></span><br><span class="line">            $<span class="class"><span class="keyword">class</span> </span>= $parameter-&gt;getClass();</span><br><span class="line"></span><br><span class="line">            <span class="keyword">if</span> ($<span class="class"><span class="keyword">class</span>)</span></span><br><span class="line"><span class="class">            </span>&#123;</span><br><span class="line">                array_splice($parameters, $key, <span class="number">0</span>, [</span><br><span class="line">                        <span class="keyword">new</span> $<span class="class"><span class="keyword">class</span>-&gt;<span class="title">name</span>()</span></span><br><span class="line">                ]);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        call_user_func_array([</span><br><span class="line">                $instance,</span><br><span class="line">                $method</span><br><span class="line">        ], $parameters);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">app::run(<span class="keyword">new</span> Database(), <span class="string">'test'</span>);</span><br></pre></td></tr></table></figure>
<h3 id="反射机制实现依赖注入"><a href="#反射机制实现依赖注入" class="headerlink" title="反射机制实现依赖注入"></a>反射机制实现依赖注入</h3><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br></pre></td><td class="code"><pre><span class="line">&lt;?php</span><br><span class="line">namespace Models;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Car</span></span></span><br><span class="line"><span class="class"></span>&#123;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">namespace Framework;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">App</span></span></span><br><span class="line"><span class="class"></span>&#123;</span><br><span class="line">    public <span class="function"><span class="keyword">function</span> <span class="title">getInstance</span>(<span class="params">$className</span>)</span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        <span class="comment">//实例化 ReflectionClass 对象</span></span><br><span class="line">        $reflector = <span class="keyword">new</span> \ReflectionClass($className);</span><br><span class="line"></span><br><span class="line">        <span class="keyword">if</span> (!$reflector-&gt;isInstantiable()) &#123;</span><br><span class="line">            <span class="comment">//不能被实例化的逻辑</span></span><br><span class="line">            <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="comment">//获取构造器</span></span><br><span class="line">        $<span class="keyword">constructor</span> = $reflector-&gt;getConstructor();</span><br><span class="line"></span><br><span class="line">        //如果没有构造器，直接实例化</span><br><span class="line">        if (!$<span class="keyword">constructor</span>) &#123;</span><br><span class="line">            <span class="comment">//这里用了变量来动态的实例化类</span></span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">new</span> $className;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">$app = <span class="keyword">new</span> App();</span><br><span class="line">$car = $app-&gt;getInstance(<span class="string">'Models\Car'</span>);</span><br><span class="line">var_dump($car); <span class="comment">//输出 object(Models\Car)#4 (0) &#123; &#125;</span></span><br><span class="line">&lt;?php</span><br><span class="line">namespace Framework;</span><br><span class="line"></span><br><span class="line"><span class="comment">//定义一个类，用于实现依赖注入</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">App</span></span></span><br><span class="line"><span class="class"></span>&#123;</span><br><span class="line">    public <span class="function"><span class="keyword">function</span> <span class="title">getInstance</span>(<span class="params">$className</span>)</span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        <span class="comment">//实例化 ReflectionClass 对象</span></span><br><span class="line">        $reflector = <span class="keyword">new</span> \ReflectionClass($className);</span><br><span class="line"></span><br><span class="line">        <span class="keyword">if</span> (!$reflector-&gt;isInstantiable()) &#123;</span><br><span class="line">            <span class="comment">//不能被实例化的逻辑，抽象类和接口不能被实例化</span></span><br><span class="line">            <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="comment">//获取构造器</span></span><br><span class="line">        $<span class="keyword">constructor</span> = $reflector-&gt;getConstructor();</span><br><span class="line"></span><br><span class="line">        //如果没有构造器，也就是没有依赖，直接实例化</span><br><span class="line">        if (!$<span class="keyword">constructor</span>) &#123;</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">new</span> $className;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="comment">//如果有构造器，先把构造器中的参数获取出来</span></span><br><span class="line">        $parameters = $<span class="keyword">constructor</span>-&gt;getParameters();</span><br><span class="line"></span><br><span class="line">        //再遍历 parameters ，找出每一个类的依赖，存到 dependencies 数组中</span><br><span class="line">        $dependencies = array_map(function ($parameter) &#123;</span><br><span class="line">            <span class="comment">/**</span></span><br><span class="line"><span class="comment">             * 这里是递归的去寻找每一个类的依赖，例如第一次执行的时候，程序发现汽车 Car 类依赖底盘 Chassis</span></span><br><span class="line"><span class="comment">             * 类，此时 $parameter 是一个ReflectionParameter 的实例，接着调用 ReflectionParameter</span></span><br><span class="line"><span class="comment">             * 的 getClass() 方法，获得一个 ReflectionClass 的实例，再接着调用 ReflectionClass</span></span><br><span class="line"><span class="comment">             * 的 getName() 方法，取得类名，也就是 Models\Chassis ，但此时此刻还不能直接去 new</span></span><br><span class="line"><span class="comment">             * Models\Chassis ，因为 Models\Chassis 也有依赖，故要递归的去调用 getInstance</span></span><br><span class="line"><span class="comment">             * 进一步去寻找该类的依赖，周而复始，直到触发上面的 if(!$constructor) ，停止递归。</span></span><br><span class="line"><span class="comment">             */</span></span><br><span class="line">            <span class="keyword">return</span> $<span class="keyword">this</span>-&gt;getInstance($parameter-&gt;getClass()-&gt;getName());</span><br><span class="line">        &#125;, $parameters);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//最后，使用 ReflectionClass 类提供的 newInstanceArgs ，方法去实例化类，参数将会传入构造器中</span></span><br><span class="line">        <span class="keyword">return</span> $reflector-&gt;newInstanceArgs($dependencies);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">namespace Models;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Car</span></span></span><br><span class="line"><span class="class"></span>&#123;</span><br><span class="line">    protected $chassis;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//汽车依赖底盘</span></span><br><span class="line">    public <span class="function"><span class="keyword">function</span> <span class="title">__construct</span>(<span class="params">Chassis $chassis</span>)</span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        $<span class="keyword">this</span>-&gt;chassis = $chassis;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Chassis</span></span></span><br><span class="line"><span class="class"></span>&#123;</span><br><span class="line">    protected $tyre;</span><br><span class="line">    protected $axle;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//底盘依赖轮胎和轴承</span></span><br><span class="line">    public <span class="function"><span class="keyword">function</span> <span class="title">__construct</span>(<span class="params">Tyre $tyre, Axle $axle</span>)</span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        $<span class="keyword">this</span>-&gt;tyre = $tyre;</span><br><span class="line">        $<span class="keyword">this</span>-&gt;axle = $axle;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Tyre</span></span></span><br><span class="line"><span class="class"></span>&#123;</span><br><span class="line">    protected $axle;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//轮胎也依赖轴承</span></span><br><span class="line">    public <span class="function"><span class="keyword">function</span> <span class="title">__construct</span>(<span class="params">Axle $axle</span>)</span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        $<span class="keyword">this</span>-&gt;axle = $axle;</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Axle</span></span></span><br><span class="line"><span class="class"></span>&#123;</span><br><span class="line">    <span class="comment">//轴承无依赖</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">$app = <span class="keyword">new</span> \Framework\App();</span><br><span class="line">$car = $app-&gt;getInstance(<span class="string">'Models\Car'</span>);<span class="comment">//不用$car = new Car(new Chassis(new Tyre(new Axle), new Axle()))</span></span><br><span class="line">var_dump($car);</span><br></pre></td></tr></table></figure>
<h3 id="IOC"><a href="#IOC" class="headerlink" title="IOC"></a>IOC</h3><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br></pre></td><td class="code"><pre><span class="line">&lt;?php</span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 没有IoC/DI的时候，常规的A类使用C类的示例</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Class c</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">c</span></span></span><br><span class="line"><span class="class"></span>&#123;</span><br><span class="line">    public <span class="function"><span class="keyword">function</span> <span class="title">say</span>(<span class="params"></span>)</span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        echo <span class="string">'hello'</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Class a</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">a</span></span></span><br><span class="line"><span class="class"></span>&#123;</span><br><span class="line">    private $c;</span><br><span class="line">    public <span class="function"><span class="keyword">function</span> <span class="title">__construct</span>(<span class="params"></span>)</span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        $<span class="keyword">this</span>-&gt;c = <span class="keyword">new</span> C(); <span class="comment">// 实例化创建C类</span></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    public <span class="function"><span class="keyword">function</span> <span class="title">sayC</span>(<span class="params"></span>)</span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        echo $<span class="keyword">this</span>-&gt;c-&gt;say(); <span class="comment">// 调用C类中的方法</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">$a = <span class="keyword">new</span> a();</span><br><span class="line">$a-&gt;sayC();</span><br><span class="line">&lt;?php</span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 当有了IoC/DI的容器后,a类依赖c实例注入的示例https://segmentfault.com/a/1190000007536704</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Class c</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">c</span></span></span><br><span class="line"><span class="class"></span>&#123;</span><br><span class="line">    public <span class="function"><span class="keyword">function</span> <span class="title">say</span>(<span class="params"></span>)</span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        echo <span class="string">'hello'</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Class a</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">a</span></span></span><br><span class="line"><span class="class"></span>&#123;</span><br><span class="line">    private $c;</span><br><span class="line">    public <span class="function"><span class="keyword">function</span> <span class="title">setC</span>(<span class="params">C $c</span>)</span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        $<span class="keyword">this</span>-&gt;c = $c; <span class="comment">// 实例化创建C类</span></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    public <span class="function"><span class="keyword">function</span> <span class="title">sayC</span>(<span class="params"></span>)</span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        echo $<span class="keyword">this</span>-&gt;c-&gt;say(); <span class="comment">// 调用C类中的方法</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">$c = <span class="keyword">new</span> C();</span><br><span class="line">$a = <span class="keyword">new</span> a();</span><br><span class="line">$a-&gt;setC($c);</span><br><span class="line">$a-&gt;sayC();</span><br></pre></td></tr></table></figure>
<h3 id="依赖注入-控制反转"><a href="#依赖注入-控制反转" class="headerlink" title="依赖注入 控制反转"></a>依赖注入 控制反转</h3><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br><span class="line">145</span><br><span class="line">146</span><br><span class="line">147</span><br><span class="line">148</span><br><span class="line">149</span><br><span class="line">150</span><br><span class="line">151</span><br><span class="line">152</span><br><span class="line">153</span><br><span class="line">154</span><br></pre></td><td class="code"><pre><span class="line">interface DbConnect &#123;</span><br><span class="line"></span><br><span class="line">    public <span class="function"><span class="keyword">function</span> <span class="title">connect</span>(<span class="params"></span>);</span></span><br><span class="line"><span class="function">&#125;</span></span><br><span class="line"><span class="function"></span></span><br><span class="line"><span class="function"><span class="title">class</span> <span class="title">DbA</span> <span class="title">implements</span> <span class="title">DbConnect</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    public <span class="function"><span class="keyword">function</span> <span class="title">connect</span>(<span class="params"></span>)</span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        <span class="comment">// <span class="doctag">TODO:</span> Implement test_echo() method.</span></span><br><span class="line">        echo <span class="string">'A'</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">DbB</span> <span class="title">implements</span> <span class="title">DbConnect</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    public <span class="function"><span class="keyword">function</span> <span class="title">connect</span>(<span class="params"></span>)</span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        <span class="comment">// <span class="doctag">TODO:</span> Implement test_echo() method.</span></span><br><span class="line">        echo <span class="string">"B"</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">ConnectDb</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    protected $connects;</span><br><span class="line"></span><br><span class="line">    public <span class="function"><span class="keyword">function</span> <span class="title">__construct</span>(<span class="params"></span>)</span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        $<span class="keyword">this</span>-&gt;connect = <span class="keyword">new</span> DbA();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    public <span class="function"><span class="keyword">function</span> <span class="title">connect</span>(<span class="params"></span>)</span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        echo $<span class="keyword">this</span>-&gt;connect-&gt;connect();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line">上面写法可以实现数据库连接功能，但是要切换到 B 数据库就要修改 ConnectDb 类，这样代码没法达到低耦合，也不符合编程开放封闭原则。我们可以把连接的类用函数传参的方式传进 ConnectDb 构造函数里.</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">ConnectDb</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    protected $connects;</span><br><span class="line"></span><br><span class="line">    public <span class="function"><span class="keyword">function</span> <span class="title">__construct</span>(<span class="params">DbConnect $dbConnect</span>)</span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        $<span class="keyword">this</span>-&gt;connect = $dbConnect;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    public <span class="function"><span class="keyword">function</span> <span class="title">connect</span>(<span class="params"></span>)</span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        echo $<span class="keyword">this</span>-&gt;connect-&gt;connect();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">$ConnectDb = <span class="keyword">new</span> ConnectDb(<span class="keyword">new</span> DbA());</span><br><span class="line">$ConnectDb-&gt;connect();</span><br><span class="line">这样我们就可以不修改 ConnectDb 而是用构造函数参数传递的方式切换数据库，这就是控制反转（感觉好像工厂模式。。。），不需要自己内容修改，通过外部传递参数，这种由外部负责其依赖需求的行为，称控制反转（IoC）</span><br><span class="line"></span><br><span class="line">不通过自己内部 <span class="keyword">new</span> 对象或者实例，而是通过函数或者构造函数传递进来。称为依赖注入（DI）</span><br><span class="line"></span><br><span class="line">反射</span><br><span class="line"></span><br><span class="line">刚毕业那会面试一家公司面试就问我了不了解反射，当时给我问的一懵。工作这么长时间了其实还是不了解。。。。</span><br><span class="line"></span><br><span class="line">反射其实就是根据类名返回这个类的任何信息，比如该类的方法，参数，属性等等</span><br><span class="line"></span><br><span class="line">ReflectionClass 类报告了一个类的有关信息。</span><br><span class="line"><span class="comment">//   — 初始化 ReflectionClass 类</span></span><br><span class="line">$reflectionClass = <span class="keyword">new</span> ReflectionClass(<span class="string">'ConnectDb'</span>);</span><br><span class="line"></span><br><span class="line"><span class="comment">//   — 获取类的构造函数   一个 ReflectionMethod 对象，反射了类的构造函数，或者当类不存在构造函数时返回 NULL。</span></span><br><span class="line">$<span class="keyword">constructor</span>     = $reflectionClass-&gt;getConstructor();</span><br><span class="line"></span><br><span class="line">//   - 获取构造函数所有依赖参数</span><br><span class="line">$dependencies    = $<span class="keyword">constructor</span>-&gt;getParameters();</span><br><span class="line"></span><br><span class="line">//   - 创建类的新的实例。给出的参数将会传递到类的构造函数。</span><br><span class="line">$ConnectDb       = $reflectionClass-&gt;newInstance();</span><br><span class="line"></span><br><span class="line">//   - 创建一个类的新实例，给出的参数将传递到类的构造函数。这个参数以 array 形式传递到类的构造函数 返回值 返回类的实例</span><br><span class="line">$ConnectDb       = $reflectionClass-&gt;newInstanceArgs($dependencies);</span><br><span class="line">我们可以创建一个方法，利用反射的机制拿到 ConnectDb 类的构造函数，然后拿到构造函数的参数对象，用递归的方法创建参数依赖，最后调用 newInstanceArgs 方法生成 ConnectDb 实例</span><br><span class="line"></span><br><span class="line">interface DbConnect &#123;</span><br><span class="line"></span><br><span class="line">    public <span class="function"><span class="keyword">function</span> <span class="title">connect</span>(<span class="params"></span>);</span></span><br><span class="line"><span class="function">&#125;</span></span><br><span class="line"><span class="function"></span></span><br><span class="line"><span class="function"><span class="title">class</span> <span class="title">DbA</span> <span class="title">implements</span> <span class="title">DbConnect</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    public <span class="function"><span class="keyword">function</span> <span class="title">connect</span>(<span class="params"></span>)</span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        <span class="comment">// <span class="doctag">TODO:</span> Implement test_echo() method.</span></span><br><span class="line">        echo <span class="string">'A'</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">DbB</span> <span class="title">implements</span> <span class="title">DbConnect</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    public <span class="function"><span class="keyword">function</span> <span class="title">connect</span>(<span class="params"></span>)</span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        <span class="comment">// <span class="doctag">TODO:</span> Implement test_echo() method.</span></span><br><span class="line">        echo <span class="string">"B"</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">ConnectDb</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    protected $connects;</span><br><span class="line">    <span class="comment">//反射是不能动态创建接口的</span></span><br><span class="line">    public <span class="function"><span class="keyword">function</span> <span class="title">__construct</span>(<span class="params">DbA $dbConnect</span>)</span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        $<span class="keyword">this</span>-&gt;connect = $dbConnect;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    public <span class="function"><span class="keyword">function</span> <span class="title">connect</span>(<span class="params"></span>)</span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        echo $<span class="keyword">this</span>-&gt;connect-&gt;connect();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">make</span> (<span class="params">$concrete</span>) </span>&#123;</span><br><span class="line">    <span class="comment">//   — 初始化 ReflectionClass 类</span></span><br><span class="line">    $reflectionClass = <span class="keyword">new</span> ReflectionClass($concrete);</span><br><span class="line">    <span class="comment">//   — 获取类的构造函数   一个 ReflectionMethod 对象，反射了类的构造函数，或者当类不存在构造函数时返回 NULL。</span></span><br><span class="line">    $<span class="keyword">constructor</span>     = $reflectionClass-&gt;getConstructor();</span><br><span class="line"></span><br><span class="line">    //如果不需要传递参数直接返回实例</span><br><span class="line">    if (is_null($<span class="keyword">constructor</span>)) &#123;</span><br><span class="line">        <span class="keyword">return</span> $reflectionClass-&gt;newInstance();</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">    <span class="comment">//   - 获取构造函数所有依赖参数</span></span><br><span class="line">        $dependencies    = $<span class="keyword">constructor</span>-&gt;getParameters();</span><br><span class="line">        $instance = getdependencies($dependencies);</span><br><span class="line">        return $reflectionClass-&gt;newInstanceArgs($instance);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">function getdependencies($parameter)</span><br><span class="line">&#123;</span><br><span class="line">    $dependencies = [];</span><br><span class="line">    foreach ($parameter <span class="keyword">as</span> $paramete) &#123;</span><br><span class="line">        <span class="comment">//返回对象实例 object 所属类的名字。返回对象实例 object 所属类的名字。 如果 object 不是一个对象则返回 FALSE。</span></span><br><span class="line">        $dependencies[] = make($paramete-&gt;getClass()-&gt;name);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> $dependencies;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">$ConnectDb = make(<span class="string">'ConnectDb'</span>);</span><br><span class="line">$ConnectDb-&gt;connect();</span><br><span class="line">总结：</span><br><span class="line"></span><br><span class="line">控制反转（IoC）：不修改类内部自身，通过外部参数传递的方式，由外部负责其依赖需求的行为。</span><br><span class="line">依赖注入（DI） ：不通过自己 <span class="keyword">new</span> 或实例实例化，通过函数或者构造函数传递进来。</span><br><span class="line">反射：根据类名获取类的信息，方法、属性、参数等等https:<span class="comment">//learnku.com/articles/32310</span></span><br></pre></td></tr></table></figure>
<h3 id="IOC-demo"><a href="#IOC-demo" class="headerlink" title="IOC demo"></a>IOC demo</h3><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line">interface Board &#123;</span><br><span class="line">        public <span class="function"><span class="keyword">function</span> <span class="title">type</span>(<span class="params"></span>);</span></span><br><span class="line"><span class="function">    &#125;</span></span><br><span class="line"><span class="function"></span></span><br><span class="line"><span class="function">    <span class="title">class</span> <span class="title">CommonBoard</span> <span class="title">implements</span> <span class="title">Board</span> </span>&#123;</span><br><span class="line">        public <span class="function"><span class="keyword">function</span> <span class="title">type</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">            echo <span class="string">'普通键盘'</span>;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="class"><span class="keyword">class</span> <span class="title">MechanicalKeyboard</span> <span class="title">implements</span> <span class="title">Board</span> </span>&#123;</span><br><span class="line">        public <span class="function"><span class="keyword">function</span> <span class="title">type</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">            echo <span class="string">'机械键盘'</span>;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="class"><span class="keyword">class</span> <span class="title">Computer</span> </span>&#123;</span><br><span class="line">        protected $keyboard;</span><br><span class="line"></span><br><span class="line">        public <span class="function"><span class="keyword">function</span> <span class="title">__construct</span> (<span class="params">Board $keyboard</span>) </span>&#123;</span><br><span class="line">            $<span class="keyword">this</span>-&gt;keyboard = $keyboard;</span><br><span class="line">        &#125;</span><br><span class="line">        public <span class="function"><span class="keyword">function</span> <span class="title">type</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">            $<span class="keyword">this</span>-&gt;keyboard-&gt;type();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    $computer = <span class="keyword">new</span> Computer(<span class="keyword">new</span> MechanicalKeyboard());</span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Container</span></span></span><br><span class="line"><span class="class"></span>&#123;</span><br><span class="line">    protected $binds;</span><br><span class="line"></span><br><span class="line">    protected $instances;</span><br><span class="line"></span><br><span class="line">    public <span class="function"><span class="keyword">function</span> <span class="title">bind</span>(<span class="params">$abstract, $concrete</span>)</span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> ($concrete <span class="keyword">instanceof</span> Closure) &#123;</span><br><span class="line">            $<span class="keyword">this</span>-&gt;binds[$abstract] = $concrete;</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            $<span class="keyword">this</span>-&gt;instances[$abstract] = $concrete;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    public <span class="function"><span class="keyword">function</span> <span class="title">make</span>(<span class="params">$abstract, $parameters = []</span>)</span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (isset($<span class="keyword">this</span>-&gt;instances[$abstract])) &#123;</span><br><span class="line">            <span class="keyword">return</span> $<span class="keyword">this</span>-&gt;instances[$abstract];</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        array_unshift($parameters, $<span class="keyword">this</span>);<span class="comment">//闭包的时候第一个参数为$this</span></span><br><span class="line"></span><br><span class="line">        <span class="keyword">return</span> call_user_func_array($<span class="keyword">this</span>-&gt;binds[$abstract], $parameters);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line">   $container = <span class="keyword">new</span> Container;</span><br><span class="line"></span><br><span class="line">    $container-&gt;bind(<span class="string">'Board'</span>, <span class="function"><span class="keyword">function</span>(<span class="params">$container</span>)</span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> CommonBoard;</span><br><span class="line">    &#125;);</span><br><span class="line">    <span class="comment">//当我需要Computer类的时候你就给我实例化Computer类</span></span><br><span class="line">    $container-&gt;bind(<span class="string">'Computer'</span>,<span class="function"><span class="keyword">function</span>(<span class="params">$container,$module</span>)</span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> Computer($container-&gt;make($<span class="built_in">module</span>));</span><br><span class="line">    &#125;);</span><br><span class="line"></span><br><span class="line">    $computer = $container-&gt;make(<span class="string">'Computer'</span>,[<span class="string">'Board'</span>]);<span class="comment">//对Computer进行生产返回一个实例。</span></span><br><span class="line">    echo $computer-&gt;type();</span><br><span class="line"></span><br><span class="line">    <span class="comment">//更换键盘怎么办呢？</span></span><br><span class="line"></span><br><span class="line">    $container-&gt;bind(<span class="string">'Board'</span>, <span class="function"><span class="keyword">function</span>(<span class="params">$container</span>)</span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> MechanicalKeyboard;</span><br><span class="line">    &#125;);</span><br><span class="line"></span><br><span class="line">    $container-&gt;bind(<span class="string">'Computer'</span>,<span class="function"><span class="keyword">function</span>(<span class="params">$container,$module</span>)</span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> Computer($container-&gt;make($<span class="built_in">module</span>));</span><br><span class="line">    &#125;);</span><br><span class="line"></span><br><span class="line">    $computer = $container-&gt;make(<span class="string">'Computer'</span>,[<span class="string">'Board'</span>]);</span><br><span class="line">    <span class="comment">//https://3v4l.org/3krab</span></span><br></pre></td></tr></table></figure>
<p><a href="https://learnku.com/articles/24200" target="_blank" rel="noopener">反射机制实现依赖注入</a></p>
<p><a href="https://phpcasts.org/topics/21" target="_blank" rel="noopener">PHP中的依赖注入（DI）容器</a></p>
<p><a href="https://laravel-china.org/articles/19195" target="_blank" rel="noopener">Laravel 服务容器，IoC,DI</a></p>
<p><a href="https://laravel-china.org/topics/843/laravel-dependency-injection-principle" target="_blank" rel="noopener"> Laravel 依赖注入原理</a></p>
<p><a href="https://laravel-china.org/articles/14145/rely-on-inversion-control-inversion-ioc-container-dependency-injection" target="_blank" rel="noopener">浅析依赖倒转、控制反转、IoC 容器、依赖注入</a></p>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/php/" rel="tag"># php</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2018/11/20/hello-world/" rel="next" title="hexo搭建博客">
                <i class="fa fa-chevron-left"></i> hexo搭建博客
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2018/11/23/基本数据结构算法/" rel="prev" title="基本数据结构算法">
                基本数据结构算法 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
          <div class="comments" id="comments">
             <div id="gitment-container"></div>
         </div>
  




        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope="" itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name">苏生不惑</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">382</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">37</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/sushengbuhuo" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="mysusheng@gmail.com" target="_blank" title="E-Mail">
                      
                        <i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://plus.google.com/mysusheng" target="_blank" title="Google">
                      
                        <i class="fa fa-fw fa-google"></i>Google</a>
                  </span>
                
            </div>
          

          
          

          
          
            <div class="links-of-blogroll motion-element links-of-blogroll-block">
              <div class="links-of-blogroll-title">
                <i class="fa  fa-fw fa-link"></i>
                Links
              </div>
              <ul class="links-of-blogroll-list">
                
                  <li class="links-of-blogroll-item">
                    <a href="http://v2ex.com/" title="v2ex" target="_blank">v2ex</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://www.fanhaobai.com/" title="fanhaobai" target="_blank">fanhaobai</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://yuanxuxu.com/archives/" title="yuanxuxu" target="_blank">yuanxuxu</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://www.snail-c.cn/article" title="snail-c" target="_blank">snail-c</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="http://showcj.com/archives" title="showcj" target="_blank">showcj</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="http://vultr.aicnm.com/%E6%9C%80%E6%96%B0Vultr%E6%B3%A8%E5%86%8C%E5%8F%8AVPS%E8%B4%AD%E4%B9%B0%E5%9B%BE%E6%96%87%E6%95%99%E7%A8%8B/" title="vultr" target="_blank">vultr</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://www.lucissfer.com/" title="lucissfer" target="_blank">lucissfer</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://blog.csdn.net/fdipzone/article/details/79352685" title="傲雪星枫" target="_blank">傲雪星枫</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://www.yoby123.cn/index.php/category/default/" title="小白的分享" target="_blank">小白的分享</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://www.cnblogs.com/52fhy/p/5819995.html" title="PHP攻城狮" target="_blank">PHP攻城狮</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://blog.jiaojie.site/" title="php" target="_blank">php</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://sphard.com/archives/" title="sphard" target="_blank">sphard</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://yuanxuxu.com/archives/" title="LNMP技术栈笔记" target="_blank">LNMP技术栈笔记</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="http://www.coding10.com/" title="学习 Laravel" target="_blank">学习 Laravel</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://shuwoom.com/?page_id=929" title="区块链学习指南" target="_blank">区块链学习指南</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://greenlightt.github.io/archives/" title="greenlightt" target="_blank">greenlightt</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://www.0php.net/archives/" title="0php" target="_blank">0php</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="http://www.fordba.com/category/mysql" title="mysql" target="_blank">mysql</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://www.itcodemonkey.com/" title="程序员" target="_blank">程序员</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://www.yanshuo.me/r/v2ex" title="言说" target="_blank">言说</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://www.timiguo.com/archive.html" title="提米果的博客" target="_blank">提米果的博客</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://phpartisan.cn/news/112.html" title="phpartisan" target="_blank">phpartisan</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://www.cnblogs.com/52fhy/" title="飞鸿影" target="_blank">飞鸿影</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="http://www.54php.cn/" title="54php" target="_blank">54php</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://www.lazyman.vip/" title="营销" target="_blank">营销</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://www.njphper.com/archives/" title="做人呢最重要的就是开心" target="_blank">做人呢最重要的就是开心</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://www.h57.pw/" title="php 初心者" target="_blank">php 初心者</a>
                  </li>
                
              </ul>
            </div>
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#依赖注入"><span class="nav-number">1.</span> <span class="nav-text">依赖注入</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#IoC-容器类"><span class="nav-number">2.</span> <span class="nav-text">IoC 容器类</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#魔术方法"><span class="nav-number">3.</span> <span class="nav-text">魔术方法</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#控制反转"><span class="nav-number">4.</span> <span class="nav-text">控制反转</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#依赖注入原理"><span class="nav-number">5.</span> <span class="nav-text">依赖注入原理</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#反射机制实现依赖注入"><span class="nav-number">6.</span> <span class="nav-text">反射机制实现依赖注入</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#IOC"><span class="nav-number">7.</span> <span class="nav-text">IOC</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#依赖注入-控制反转"><span class="nav-number">8.</span> <span class="nav-text">依赖注入 控制反转</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#IOC-demo"><span class="nav-number">9.</span> <span class="nav-text">IOC demo</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>

<div class="copyright">&copy; <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">苏生不惑</span>

  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Gemini</a> v5.1.4</div>



<div>
<span id="showDays"></span>

</div>

<span id="busuanzi_container_site_pv">
   总访问量:<span id="busuanzi_value_site_pv"></span>次
</span>



  <span class="post-meta-divider">|</span>



<div class="theme-info">
  <div class="powered-by"></div>
  <span class="post-count">博客全站共773.8k字</span>
</div>
<script>
var birthDay = new Date("11/20/2018");
var now = new Date();
var duration = now.getTime() - birthDay.getTime();
var total= Math.floor(duration / (1000 * 60 * 60 * 24));
document.getElementById("showDays").innerHTML = "本站已运行 "+total+" 天";
</script>

        
<div class="busuanzi-count">
  <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv">
      <i class="fa fa-user"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      人次
    </span>
  

  
    <span class="site-pv">
      <i class="fa fa-eye"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      次
    </span>
  
</div>








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  


  











  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  

  
  
    <script type="text/javascript" src="/lib/canvas-nest/canvas-nest.min.js"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  











<script type="text/javascript">
    (function() {
        // 匿名函数，防止污染全局变量
        var utterances = document.createElement('script');
        utterances.type = 'text/javascript';
        utterances.async = true;
        utterances.setAttribute('issue-term','0')
        utterances.setAttribute('theme','')
        utterances.setAttribute('repo','sushengbuhuo/laravel_ioc_demo')
        utterances.crossorigin = 'anonymous';
        utterances.src = 'https://utteranc.es/client.js';
        // content 是要插入评论的地方
        document.getElementById('gitment-container').appendChild(utterances);
    })();
</script>


  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  

  

  

  

  
<script>
  ((window.gitter = {}).chat = {}).options = {
    //room替换成自己的聊天室名称即可，room的名称规则是：username/roomname
    room: 'sushengbuhuo-chat/mychat'
  };
</script>
<script src="https://sidecar.gitter.im/dist/sidecar.v1.js" async defer></script>

</body>
</html>
